#define _CRT_SECURE_NO_WARNINGS
#include"SeqList.h"

void SLInit(SL* ps)
{
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

//void SLInit(SL* ps)
//{
//	SLDataType* p = (SLDataType*)malloc(4 * sizeof(SLDataType));
//	if (NULL == p)
//	{
//		perror("malloc fail");
//		exit(1);
//	}
//
//	ps->a = p;
//	ps->size = 0;
//	ps->capacity = 4;
//}


void SLDestroy(SL* ps)
{
	assert(ps);
	if (ps->a)
	{
		free(ps->a);
	}
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

//void SLPrint(SL ps)
//{
//
//	for (int i = 0; i < ps.size; i++)
//	{
//		printf("%d ", ps.a[i]);
//	}
//	printf("\n");
//}

void SLCheckCapacity(SL* ps)
{
	assert(ps);

	if(ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity ? 2 * ps->capacity : 4;
		SLDataType* p = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
		if (NULL == p)
		{
			perror("malloc fail");
			exit(1);
		}
		ps->a = p;
		ps->capacity = newcapacity;
	}
}


void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);

	ps->a[ps->size++] = x;
}


void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size);

	ps->size--;
}


void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);

	void SLCheckCapacity(SL * ps);
	
	for (int i = ps->size; i > 0; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->size++;
}


void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);

	for(int i = 0; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}

	ps->size--;
}



int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}

	return -1;
}


void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SLCheckCapacity(ps);

	for (int i = ps->size - 1; i >= pos; i--)
	{
		ps->a[i + 1] = ps->a[i];
	}

	ps->a[pos] = x;
	ps->size++;
}


void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos <ps->size);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}

	ps->size--;
}
